package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.fastdfsclient.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import com.usian.wemedia.utils.KODOUtils;
import com.usian.wemedia.utils.OSSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private KODOUtils kodoUtils;

    @Value("${wmaterial.baseurl}")
    private String baseUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        WmUser wmUser =  WmThreadLocalUtils.getUser();
        WmMaterial wmMaterial = null;
        if(multipartFile==null){
            CatchCustomException.catchs(20001,"文件不能为空！");
        }
        // 1. 判断文件Md5值  -->

        // 2. 判断用户是否登录
        if(wmUser==null || wmUser.getId()==null){
            // 没有登录
            CatchCustomException.catchs(20001,"没有文件上传权限！");
        }
        String imagesUrl = "";
        try {
            // 阿里云
//            阿里云运行的↓
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            imagesUrl =  ossClientUtil.saveImage(multipartFile);
            // 七牛云
//            ↓七牛运行的
//            imagesUrl =  kodoUtils.saveImages(multipartFile);
//            这个不是
//            imagesUrl =  fastDFSClient.uploadFile(multipartFile);
//           一直打开↓
            wmMaterial =  saveUrlByWmMaterial(imagesUrl,wmUser);
            // 5. 把刚才上传的图片路径  返回给前端
//            这个也不用管
            //wmMaterial.setUrl(baseUrl + wmMaterial.getUrl());
        }catch (Exception e){
            CatchCustomException.catchs(20001,"上传图片出现未知错误！");
        }
        return ResponseResult.okResult(wmMaterial);
    }



    private WmMaterial saveUrlByWmMaterial(String imageUrl,WmUser wmUser){
        // 3. 是  上传  获取fileId --》OSS -->KODO
        // 3.1  创建媒体资源对象
        // 3.2   封装各种数据
        // 3.3 保存
        // 4. 否  提示错误信息
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(imageUrl);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        this.save(wmMaterial);
        return wmMaterial;
    }
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 1. 判断参数
        if(dto==null){
            CatchCustomException.catchs(20003,"参数不能为空！");
        }
        // 2. 初始化分页参数
        dto.checkParam();
        // 3. 默认获取用户ID
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            CatchCustomException.catchs(20003,"没有登录！");
        }
        // 拼接查询条件
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper();
        Integer uid = wmUser.getId();
        lambdaQueryWrapper.eq(WmMaterial::getUserId,uid);
        // 收藏是否为空  不为空 拼接收藏条件
        if(dto.getIsCollection() != null && dto.getIsCollection().shortValue()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        // 按照时间排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        // 4. 根据用户ID 查询对应的素材
        Page page = new Page(dto.getPage(),dto.getSize());
        IPage<WmMaterial> iPage = this.page(page, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(iPage.getCurrent(),iPage.getSize(),iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }



    @Override
    public ResponseResult delPicture(Integer id) {
        if(id == null){
            CatchCustomException.catchs(20003,"id不能为空");
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            CatchCustomException.catchs(20003,"用户尚未登录，不能删除！");
        }
        // 查询对应关系
        Integer count =  wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId,id));
        if(count>0){
            CatchCustomException.catchs(20003,"素材已经引用，不能删除！");
        }
        boolean result = this.remove(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId,wmUser.getId()).eq(WmMaterial::getId,id));
        if(result){
            // 删除对应 OSS 、KODO 、 FastDfs
            // fileId   =   group1/M00/00/00/wKjThGNOR-KAGneZAAASweNeHFM103.png
            //fastDFSClient.delFile("");
        }
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        // 1. 检查参数
        if(id == null){
            CatchCustomException.catchs(20003,"ID为空，不能操作！");
        }
        if(type >1 || type < 0){
            CatchCustomException.catchs(20003,"收藏状态有误，不能操作！");
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser == null){
            CatchCustomException.catchs(20003,"用户尚未登录，不能操作！");
        }
        // 调用修改语句  update set  where
        this.update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,wmUser.getId()));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
